package com.codegeek.project.slope.controller;

import com.codegeek.common.utils.poi.ExcelUtil;
import com.codegeek.framework.aspectj.lang.annotation.Log;
import com.codegeek.framework.aspectj.lang.enums.BusinessType;
import com.codegeek.framework.web.controller.BaseController;
import com.codegeek.framework.web.domain.AjaxResult;
import com.codegeek.framework.web.page.TableDataInfo;
import com.codegeek.project.slope.domain.SlopeSubscribeDetail;
import com.codegeek.project.slope.domain.SlopeSubscribeExport;
import com.codegeek.project.slope.domain.SlopeSubscriber;
import com.codegeek.project.slope.service.ISlopeSubscribeDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 订阅详情Controller
 *
 * @author codegeek
 * @date 2020-02-17
 */
@RestController
@RequestMapping("/slope/detail")
@Api(value = "订阅详情Controller", tags = {"订阅详情操作接口"})
public class SlopeSubscribeDetailController extends BaseController {
    @Autowired
    private ISlopeSubscribeDetailService slopeSubscribeDetailService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    /**
     * 查询订阅详情列表
     */
    @ApiOperation("查询订阅详情列表")
    @PreAuthorize("@ss.hasPermi('slope:detail:list')")
    @GetMapping("/list")
    public TableDataInfo list(SlopeSubscribeDetail slopeSubscribeDetail) {
        startPage();
        if (slopeSubscribeDetail.getEndTime() != null && !slopeSubscribeDetail.getEndTime().equals("")) {
            slopeSubscribeDetail.setEndTime(slopeSubscribeDetail.getEndTime() + " 23:59:59");
        }
        List<SlopeSubscribeDetail> allList = new LinkedList<>();
        if (slopeSubscribeDetail.getUserName() != null && !slopeSubscribeDetail.getUserName().equals("")) {
            try {
                String subscriberId = "";
                List<Map<String, Object>> subscriberArr = jdbcTemplate.queryForList(" select subscriber_id from slope_subscriber where subscribe_nick_name like '%" + slopeSubscribeDetail.getUserName() + "%'");
                HashSet<Long> containId = new HashSet<>();
                for (Map<String, Object> map : subscriberArr) {
                    slopeSubscribeDetail.setUserName(map.get("subscriber_id").toString());
                    List<SlopeSubscribeDetail> list = slopeSubscribeDetailService.selectSlopeSubscribeDetailList(slopeSubscribeDetail);
                    if (allList.size() != 0) {
                        for (SlopeSubscribeDetail detail : list) {
                            if (!containId.contains(detail.getSubscribeDetailId())) {
                                allList.add(detail);
                                containId.add(detail.getSubscribeDetailId());
                            }
                        }
                    } else {
                        allList = list;
                        for (SlopeSubscribeDetail temp : allList) {
                            containId.add(temp.getSubscribeDetailId());
                        }
                    }
                }
            } catch (Exception e) {
            }
        } else {
            allList = slopeSubscribeDetailService.selectSlopeSubscribeDetailList(slopeSubscribeDetail);
        }

        for (SlopeSubscribeDetail detail : allList) {
            String subscriber = detail.getSubscriber();
            Map sqlPlaceholder = new HashMap();
            StringBuilder sql = new StringBuilder(
                    " select * from slope_subscriber where INSTR(:arr,'%' + subscriber_id + '%')"
            );
            sqlPlaceholder.put("arr", subscriber);
            List<SlopeSubscriber> slopeSubscribers = namedParameterJdbcTemplate.query(sql.toString(), sqlPlaceholder, BeanPropertyRowMapper.newInstance(SlopeSubscriber.class));
            detail.setSlopeSubscribers(slopeSubscribers);
        }

        return getDataTable(allList);
    }

    /**
     * 导出订阅详情列表
     */
    @ApiOperation("导出订阅详情列表")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('slope:detail:export')")
    @GetMapping("/export")
    public AjaxResult export(SlopeSubscribeDetail slopeSubscribeDetail) {
        if (slopeSubscribeDetail.getEndTime() != null && !slopeSubscribeDetail.getEndTime().equals("")) {
            slopeSubscribeDetail.setEndTime(slopeSubscribeDetail.getEndTime() + " 23:59:59");
        }
        List<SlopeSubscribeDetail> allList = new LinkedList<>();
        if (slopeSubscribeDetail.getUserName() != null && !slopeSubscribeDetail.getUserName().equals("")) {
            try {
                String subscriberId = "";
                List<Map<String, Object>> subscriberArr = jdbcTemplate.queryForList(" select subscriber_id from slope_subscriber where subscribe_nick_name like '%" + slopeSubscribeDetail.getUserName() + "%'");
                HashSet<Long> containId = new HashSet<>();
                for (Map<String, Object> map : subscriberArr) {
                    slopeSubscribeDetail.setUserName(map.get("subscriber_id").toString());
                    List<SlopeSubscribeDetail> list = slopeSubscribeDetailService.selectSlopeSubscribeDetailList(slopeSubscribeDetail);
                    if (allList.size() != 0) {
                        for (SlopeSubscribeDetail detail : list) {
                            if (!containId.contains(detail.getSubscribeDetailId())) {
                                allList.add(detail);
                                containId.add(detail.getSubscribeDetailId());
                            }
                        }
                    } else {
                        allList = list;
                        for (SlopeSubscribeDetail temp : allList) {
                            containId.add(temp.getSubscribeDetailId());
                        }
                    }
                }
            } catch (Exception e) {
            }
        } else {
            allList = slopeSubscribeDetailService.selectSlopeSubscribeDetailList(slopeSubscribeDetail);
        }

        for (SlopeSubscribeDetail detail : allList) {
            String subscriber = detail.getSubscriber();
            Map sqlPlaceholder = new HashMap();
            StringBuilder sql = new StringBuilder(
                    " select * from slope_subscriber where INSTR(:arr,'%' + subscriber_id + '%')"
            );
            sqlPlaceholder.put("arr", subscriber);
            List<SlopeSubscriber> slopeSubscribers = namedParameterJdbcTemplate.query(sql.toString(), sqlPlaceholder, BeanPropertyRowMapper.newInstance(SlopeSubscriber.class));
            detail.setSlopeSubscribers(slopeSubscribers);
        }


        List<SlopeSubscribeExport> exports = new LinkedList<>();
        Long seqIndex = 1L;
        for (SlopeSubscribeDetail detail : allList) {
            SlopeSubscribeExport export = new SlopeSubscribeExport();
            export.setSeq(seqIndex);
            export.setMessage(detail.getMessage());
            export.setSendNum(detail.getSlopeSubscribers().size() + "");
            String userName = "";
            for (int i = 0; i < detail.getSlopeSubscribers().size(); i++) {
                userName += detail.getSlopeSubscribers().get(i).getSubscribeNickName() + ",";
            }
            export.setSendPeople(userName.substring(0, userName.length() > 0 ? userName.length() - 1: userName.length()));
            export.setSendTime(detail.getSendTime());
            exports.add(export);
            ++seqIndex;
        }
        ExcelUtil<SlopeSubscribeExport> util = new ExcelUtil<>(SlopeSubscribeExport.class);
        return util.exportExcel(exports, "detail");
    }

    /**
     * 获取订阅详情详细信息
     */
    @ApiOperation("获取订阅详情详细信息")
    @GetMapping(value = "/getInfo/{subscribeDetailId}")
    public AjaxResult getInfo(@PathVariable("subscribeDetailId") Long subscribeDetailId) {
        return AjaxResult.success(slopeSubscribeDetailService.selectSlopeSubscribeDetailById(subscribeDetailId));
    }

    /**
     * 新增订阅详情
     */
    @ApiOperation("新增订阅详情")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SlopeSubscribeDetail slopeSubscribeDetail) {
        return toAjax(slopeSubscribeDetailService.insertSlopeSubscribeDetail(slopeSubscribeDetail));
    }

//    /**
//     * 修改订阅详情
//     */
//    @ApiOperation("修改订阅详情")
//    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
//    public AjaxResult edit(@RequestBody SlopeSubscribeDetail slopeSubscribeDetail)
//    {
//        return toAjax(slopeSubscribeDetailService.updateSlopeSubscribeDetail(slopeSubscribeDetail));
//    }

    /**
     * 删除订阅详情
     */
    @ApiOperation("删除订阅详情")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{subscribeDetailIds}")
    @PreAuthorize("@ss.hasPermi('slope:detail:remove')")
    public AjaxResult remove(@PathVariable Long[] subscribeDetailIds) {
        return toAjax(slopeSubscribeDetailService.deleteSlopeSubscribeDetailByIds(subscribeDetailIds));
    }
}
